package in

import (
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"strconv"
	"strings"

	"github.com/gogf/gf/net/ghttp"
)

//返回文件
//@path,文件路径
//@names,前端显示文件名称,可选,默认当前文件名称
func returnFile(w http.ResponseWriter, path string, names ...string) error {
	file, err := os.Open(path)
	if err != nil {
		return err
	}
	name := getPathName(path)
	if len(names) > 0 && len(names[0]) != 0 {
		name = names[0]
	}
	fileHeader := make([]byte, 512)
	file.Read(fileHeader)
	fileStat, _ := file.Stat()
	w.Header().Set("Content-Disposition", "attachment; filename="+name)
	w.Header().Set("Content-Type", http.DetectContentType(fileHeader))
	w.Header().Set("Content-Length", strconv.FormatInt(fileStat.Size(), 10))
	file.Seek(0, 0)
	io.Copy(w, file)
	return nil
}

func getPathName(path string) string {
	n := strings.LastIndex(path, "/")
	if n == -1 {
		return "file"
	}
	return path[n+1:]
}

//读取文件
func getFileBytes(r *ghttp.Request, fileName string) []byte {
	f, err := r.GetUploadFile(fileName).Open()
	CheckErr(err)
	bs, err := ioutil.ReadAll(f)
	CheckErr(err)
	return bs
}

//保存文件
func saveFile(r *ghttp.Request, fileName, path string) string {
	newFileName, err := r.GetUploadFile(fileName).Save(path)
	CheckErr(err)
	return newFileName
}
